package com.hmsg.health.security.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.hmsg.health.param.AccessToken;
import com.hmsg.health.security.TokenManager;
import com.hmsg.health.utils.CodecUtil;


/**
 * 基于 Redis的令牌管理器
 *
 * @author huangyong
 * @since 1.0.0
 */
@Component
public class RedisTokenManager implements TokenManager {
	private Logger logger = LoggerFactory.getLogger(RedisTokenManager.class);
	@Autowired
	private StringRedisTemplate stringTemplate;

	/**
	 * 刷新token
	 */
	@Override
	public AccessToken createToken(String tokenkey, String userId) {
		String token = CodecUtil.createUUID();
		stringTemplate.opsForHash().put(tokenkey, userId, token);
		logger.info("===================tokenkey" + tokenkey + "userId" + userId + "token" + token);
		stringTemplate.opsForHash().put(tokenkey, token, userId);
		stringTemplate.expire(tokenkey+userId, 7, TimeUnit.DAYS);
		AccessToken accessToken = new AccessToken();
		accessToken.setAccessToken(token);
		accessToken.setUserId(userId);
		return accessToken;
	}

	@Override
	public boolean checkToken(String tokenkey, String userId, String token) {
		Object accessToken = stringTemplate.opsForHash().get(tokenkey, userId);
		if (accessToken != null && token.equals(accessToken.toString())) {
			logger.info(accessToken.toString());
			return true;
		}
		return false;
	}
	
	@Override
	public String getKey(String tokenkey,String token) {
		Set<String> keys = stringTemplate.keys("token_shuawujing_front_*");
		String res = "";
		for(String key:keys){
			String[] tokens = key.split("_");
			Object value = stringTemplate.opsForHash().get(key, tokens[tokens.length-1]);
			if(value!=null&&value.equals(token)){
				res =  tokens[tokens.length-1]; 
			}
		}
		return res;
	}

	@Override
	public boolean deleteToken(String tokenkey, String userId) {
		Object token = stringTemplate.opsForHash().get(tokenkey, userId);
		Long result = token == null ? stringTemplate.opsForHash().delete(tokenkey, userId) : stringTemplate.opsForHash().delete(tokenkey, userId, token.toString());
		return result > 0;
	}
}
